import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state: {
    // token初始是空值,登录过后设置到了cookies中,state中的token如果从cookies里面获取,便实现了数据的持久化
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    logout(state) {
      state.userInfo = {}
      state.token = ''
      removeToken()
      resetRouter()
    },
    setToken(state, token) {
      // 把token设置到vuex的state中,方便别处使用
      state.token = token
      // 把token设置到cookies中,方便数据持久
      setToken(token)
    },
    setUserInfo(state, data) {
      state.userInfo = data
    }
  },
  actions: {
    login(context, param) {
      return login(param).then(data => {
        // 响应拦截器已对返回数据解构,且成功时直接返回数据,失败时(包括数据层面的失败和状态码报错的硬性错误)
        Message.success('登录成功')
        context.commit('setToken', data)
        setTimeStamp()
      })
    },
    async getUserInfo(context) {
      const userBaseInfo = await getUserInfo()
      const userInfoDetail = await getUserDetail(userBaseInfo.userId)
      const userInfo = {
        ...userBaseInfo,
        ...userInfoDetail
      }
      context.commit('setUserInfo', userInfo)
      return userInfo
    }
  }
}

